//
//  UIView+BVideoCache.m
//  iphoneLive⁩
//
//  Created by on 2019/10/14.
//  Copyright © 2019 _ios. All rights reserved.
//

#import "UIView+BVideoCache.h"


@implementation UIView (BVideoCache)

- (void)borderColor:(UIColor *)borderColor borderW:(CGFloat)borderW cornerR:(CGFloat)cornerR{
    self.layer.cornerRadius = cornerR;
    self.layer.masksToBounds = YES;
    self.layer.borderColor = borderColor.CGColor;
    self.layer.borderWidth = borderW;
}

- (BOOL)isDisplayedInScreen{
    if(self == nil){
        return NO;
    }
    CGRect screenRect = [UIScreen mainScreen].bounds;
    CGRect rect = [self convertRect:self.frame fromView:nil];
    if(CGRectIsEmpty(rect) || CGRectIsNull(rect)){
        return NO;
    }
    if(self.hidden){
        return NO;
    }
    if(self.superview == nil){
        return NO;
    }
    if(CGSizeEqualToSize(rect.size, CGSizeZero)){
        return NO;
    }
    
    CGRect intersectionRect = CGRectIntersection(rect, screenRect);
    if(CGRectIsEmpty(intersectionRect) || CGRectIsNull(intersectionRect)){
        return NO;
    }
    return YES;
}


#pragma mark - screenshot

- (UIImage *)currentViewSnapshot{
    UIImage *image = [self nomalSnapshotImage];
    if(!image){
        image = [self openglSnapshotImage];
    }
    if(!image){
        image = [self screenshots];
    }
    return image;
}

- (UIImage *)nomalSnapshotImage
{
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, [UIScreen mainScreen].scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

- (UIImage *)openglSnapshotImage
{
    CGSize size = self.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect rect = self.frame;
    [self drawViewHierarchyInRect:rect afterScreenUpdates:YES];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}


- (UIImage *)screenshots{
    UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
    UIGraphicsBeginImageContext(screenWindow.frame.size);//全屏截图，包括window
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    return viewImage;
}

//- (UIImage *)imageForWebView
//{
//    // 1.获取WebView的宽高
//    CGSize boundsSize = self.bounds.size;
//    CGFloat boundsWidth = boundsSize.width;
//    CGFloat boundsHeight = boundsSize.height;
//    // 2.获取contentSize
//    CGSize contentSize = self.scrollView.contentSize;
//    CGFloat contentHeight = contentSize.height;
//    // 3.保存原始偏移量，便于截图后复位    CGPoint offset = self.scrollView.contentOffset;
//    // 4.设置最初的偏移量为(0,0);    [self.scrollView setContentOffset:CGPointMake(0, 0)];
//    NSMutableArray *images = [NSMutableArray array];
//    while (contentHeight > 0) {
//        // 5.获取CGContext 5.获取CGContext        UIGraphicsBeginImageContextWithOptions(boundsSize, NO, 0.0);
//        CGContextRef ctx = UIGraphicsGetCurrentContext();
//        // 6.渲染要截取的区域        [self.layer renderInContext:ctx];
//        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//        // 7.截取的图片保存起来        [images addObject:image];
//        CGFloat offsetY = self.scrollView.contentOffset.y;
//        [self.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
//        contentHeight -= boundsHeight;
//    }
//
//    // 8 webView 恢复到之前的显示区域    [self.scrollView setContentOffset:offset];
//    CGFloat scale = [UIScreen mainScreen].scale;
//    CGSize imageSize = CGSizeMake(contentSize.width * scale,
//                                  contentSize.height * scale);
//  // 9.根据设备的分辨率重新绘制、拼接成完整清晰图片    UIGraphicsBeginImageContext(imageSize);
//    [images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
//        [image drawInRect:CGRectMake(0,scale * boundsHeight * idx,scale * boundsWidth,scale * boundsHeight)];
//    }];
//    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    return fullImage;
//}

#pragma mark touch

- (UIColor*)getPixelColorAtLocation:(CGPoint)point withImage:(UIImage*)image {
    UIColor* color     = nil;
    CGImageRef inImage = image.CGImage;
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
    if (cgctx == NULL) {
        return nil;
    }
    size_t w            = CGImageGetWidth(inImage);
    size_t h            = CGImageGetHeight(inImage);
    CGRect rect         = {{0,0},{w,h}};
    CGContextDrawImage(cgctx, rect, inImage);
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        @try {
            int offset = 4*((w*round(point.y))+round(point.x));
            int alpha  = data[offset];
            int red    = data[offset+1];
            int green  = data[offset+2];
            int blue   = data[offset+3];
            color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
        }
        @catch (NSException * e) {
            NSLog(@"%@",[e reason]);
        }
        @finally {
        }
    }
    return color;
}

- (CGContextRef) createARGBBitmapContextFromImage:(CGImageRef) inImage {
    CGContextRef  context = NULL;
    CGColorSpaceRef colorSpace;
    void *  bitmapData;
    int bitmapByteCount;
    int bitmapBytesPerRow;
    size_t pixelsWide = CGImageGetWidth(inImage);
    size_t pixelsHigh = CGImageGetHeight(inImage);
    bitmapBytesPerRow = (int)(pixelsWide * 4);
    bitmapByteCount = (int)(bitmapBytesPerRow * pixelsHigh);
    colorSpace = CGColorSpaceCreateDeviceRGB();
    if (colorSpace == NULL)
    {
        fprintf(stderr, "Error allocating color spacen");
        return NULL;
    }
    bitmapData = malloc( bitmapByteCount );
    if (bitmapData == NULL)
    {
        fprintf (stderr, "Memory not allocated!");
        CGColorSpaceRelease( colorSpace );
        return NULL;
    }
    context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst);
    if (context == NULL)
    {
        free (bitmapData);
        fprintf (stderr, "Context not created!");
    }
    CGColorSpaceRelease( colorSpace );
    return context;
}




@end
